﻿Imports Co9320.NamaAlert.Model
Imports Co9320.NamaAlert.ViewModel
Imports System.Security
Imports System.Reflection
Imports System.Runtime.InteropServices
Imports System.Windows.Interop

Class Application

    ' Startup、Exit、DispatcherUnhandledException などのアプリケーション レベルのイベントは、
    ' このファイルで処理できます。

    Private WithEvents ViewModel As MainWindowViewModel
    Private WithEvents Window As MainWindow
    Private OptionsWindow As OptionsWindow
    Private Shared Path As New ApplicationPath

    Public Sub New()
        Initialize()
    End Sub

    Private Shared Sub Initialize()

        Path.UserDataFolder = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Co9320\NamaAlert\1.0.0.0")
        Path.CacheFolder = System.IO.Path.Combine(Path.UserDataFolder, "cache")
        Path.DatabaseFileName = System.IO.Path.Combine(Path.UserDataFolder, "namaalert.sdf")
        Path.ApplicationFolder = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)

    End Sub

    Protected Overrides Sub OnStartup(ByVal e As StartupEventArgs)
        MyBase.OnStartup(e)
        Debug.Print("OnStartup: {0}", System.Threading.Thread.CurrentThread.ManagedThreadId)

        ' License key
        Dim licenseKeyFile = System.IO.Path.Combine( _
            System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "licensekey.dat")
        Dim key As String
        Using fs = New System.IO.FileStream(licenseKeyFile, IO.FileMode.Open, IO.FileAccess.Read), _
              sr = New System.IO.StreamReader(fs, System.Text.Encoding.ASCII)
            key = sr.ReadLine
        End Using

        Xceed.Wpf.DataGrid.Licenser.LicenseKey = key

        'Resources("ContextMenuDataContext") = ViewModel.LivePrograms



        Window = New MainWindow

        ViewModel = New MainWindowViewModel(Path, Window.Dispatcher)
        Window.Dispatcher.Invoke(New Action(AddressOf LoadSettings), System.Windows.Threading.DispatcherPriority.Normal, Nothing)

        ViewModel.InitializeAsync()
        AddHandler ViewModel.UISettings.DataGrid.RequestSetGroup, AddressOf SetGroup

        Window.DataContext = ViewModel

        ViewModelHelper.OwnerWindow = Window
        Window.Show()
        Window.SetGroup()

    End Sub

#Region "Save/Load Settings"

    Private Sub LoadSettings()

        Dim uiSettingFile = System.IO.Path.Combine(Path.UserDataFolder, "standard_uisettings.xml")
        If System.IO.File.Exists(uiSettingFile) Then
            Try
                Using fs = New System.IO.FileStream(uiSettingFile, IO.FileMode.Open, IO.FileAccess.Read), _
                      sr = New System.IO.StreamReader(fs, System.Text.Encoding.UTF8)
                    Dim content = sr.ReadToEnd
                    ViewModel.UISettings.Deserialize(XElement.Parse(content))
                End Using
            Catch ex As Exception
                ' TODO
            End Try
        End If

        Dim pluginSettingsFile = System.IO.Path.Combine(Path.UserDataFolder, "standard_plugins.xml")
        If System.IO.File.Exists(pluginSettingsFile) Then
            Try
                Using fs = New System.IO.FileStream(pluginSettingsFile, IO.FileMode.Open, IO.FileAccess.Read), _
                      sr = New System.IO.StreamReader(fs, System.Text.Encoding.UTF8)
                    Dim content = sr.ReadToEnd
                    Dim plugins = XElement.Parse(content)

                    For Each p In plugins...<plugin>
                        Dim plugin = New PluginViewModel
                        plugin.Deserialize(p)
                        ViewModel.Plugins.Add(plugin)
                    Next

                End Using
            Catch ex As Exception
                ' TODO
            End Try
        End If

    End Sub

    Private Sub SaveSettings()
        Window.SerializedColumns()


        Try
            Using fs = New System.IO.FileStream(System.IO.Path.Combine(Path.UserDataFolder, "standard_uisettings.xml"), IO.FileMode.Create, IO.FileAccess.Write), _
                  sw = New System.IO.StreamWriter(fs, System.Text.Encoding.UTF8)
                Dim ui = ViewModel.UISettings.Serialize("ui")
                sw.WriteLine(ui.ToString)
            End Using
        Catch ex As Exception
            ' TODO message
        End Try

        Try
            Using fs = New System.IO.FileStream(System.IO.Path.Combine(Path.UserDataFolder, "standard_plugins.xml"), IO.FileMode.Create, IO.FileAccess.Write), _
                  sw = New System.IO.StreamWriter(fs, System.Text.Encoding.UTF8)
                Dim settings = <plugins>
                                   <%= From p In ViewModel.Plugins Select p.Serialize("plugin") %>
                               </plugins>
                sw.WriteLine(settings.ToString)
            End Using
        Catch ex As Exception
            Debug.Assert(False)
        End Try

    End Sub

#End Region

    Private Sub SetGroup(ByVal sender As Object, ByVal e As GroupEventArgs)
        If Window IsNot Nothing Then
            Window.SetGroup()
        End If
    End Sub

    Private Sub ViewModel_ApplicationShow(ByVal sender As Object, ByVal e As System.EventArgs) Handles ViewModel.ApplicationShow
        Window.Show()
    End Sub

    Private Sub ViewModel_ApplicationShutdown(ByVal sender As Object, ByVal e As System.EventArgs) Handles ViewModel.ApplicationShutdown
        Window.Shutdown()
    End Sub

    Private Sub ViewModel_RequestShowTopmost(ByVal sender As Object, ByVal e As BooleanEventArgs) Handles ViewModel.RequestShowTopmost
        Window.Topmost = e.State
    End Sub

    Private Sub ViewModel_RequestOptionsWindow(ByVal sender As Object, ByVal e As System.EventArgs) Handles ViewModel.RequestShowOptionsWindow
        Debug.Print("ViewModel_RequestOptionsWindow: {0}", System.Threading.Thread.CurrentThread.ManagedThreadId)
        OptionsWindow = New OptionsWindow With { _
            .DataContext = ViewModel, _
            .Topmost = ViewModel.UISettings.Topmost, _
            .Owner = Window, _
            .WindowStartupLocation = WindowStartupLocation.CenterOwner}

        ViewModelHelper.OwnerWindow = OptionsWindow

        Try
            OptionsWindow.ShowDialog()
        Catch ex As Exception
            ' Ignore
            Debug.Assert(False)
        End Try
        OptionsWindow = Nothing

        ViewModelHelper.OwnerWindow = Window
    End Sub


    Private Sub ViewModel_RequestShowImportWindow(ByVal sender As Object, ByVal e As System.EventArgs) Handles ViewModel.RequestShowImportWindow
        Dim importWindow = New ImportWindow With { _
            .Topmost = ViewModel.UISettings.Topmost, _
            .Owner = Window, _
            .WindowStartupLocation = WindowStartupLocation.CenterOwner}
        Try
            If importWindow.ShowDialog Then

            End If

        Catch ex As Exception
            Debug.Assert(False)
        End Try

    End Sub

    Private Sub ViewModel_RequestEditPluginOptions(ByVal sender As Object, ByVal e As System.EventArgs) Handles ViewModel.RequestEditPluginOptions
        Dim plugin = DirectCast(sender, PluginViewModel)
        plugin.EditOptions(OptionsWindow)
    End Sub

    Private Sub Window_Closed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Window.Closed
        SaveSettings()
    End Sub

    Private Sub Window_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Window.Loaded

    End Sub

    Private Sub Window_SizeChanged(ByVal sender As Object, ByVal e As System.Windows.SizeChangedEventArgs) Handles Window.SizeChanged
    End Sub

    Private Sub Window_StateChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Window.StateChanged
        Select Case Window.WindowState
            Case WindowState.Maximized
            Case WindowState.Minimized
            Case WindowState.Normal

        End Select
    End Sub


    Private Sub ViewModel_RequestShowBalloon(ByVal sender As Object, ByVal e As Extension.ShowBalloonTipEventArgs) Handles ViewModel.RequestShowBalloonTip
        Window.ShowBalloon(e.BalloonTipContext)
    End Sub
End Class
